package algorithm.sorty;

/**
 * @Description: 二分搜索
 * @Author Ammar
 * @Create 2023/5/2 09:12
 */
public class BinarySearch {
    /**
     * 查找元素在有序数组array中的索引
     * @param array
     * @param value
     * @return
     */
    public int indexOf(int[] array, int value) {
        if (array == null || array.length == 0) return -1;
        int begin = 0;
        int end = array.length;
        while (begin < end) {
            int mid = (begin + end) >> 1;
            if (value < array[mid]) {
                end = mid;
            } else if (value > array[mid]) {
                begin = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    /**
     * 查找v在有序数组array中的插入位置
     * @param array
     * @param value
     * @return
     */
    public int search(int[] array, int value) {
        if (array == null || array.length == 0) return -1;
        int begin = 0;
        int end = array.length;
        while (begin < end) {
            int mid = (begin + end) >> 1;
            if (value < array[mid]) {
                end = mid;
            } else {
                begin = mid + 1;
            }
        }
        return begin;
    }
}
